//表对象
var obj;
window.onload=()=>{
    obj = new Table();
    obj.tableInit();
    obj.tableInit2();

    //选择时间触发事件
    document.getElementById("currentDate").addEventListener("blur",function (e) {
        var val = this.value.split("-");
        obj.year=parseInt(val[0]);
        obj.month=parseInt(val[1]);
    })
}

//加载基层员工
function toLoadEmp(){
    $("#dg").datagrid("loadData",commonAjax("post","/jx/wlb/selectCpkEmpByDeptAndNotInPostId",{pkDept:obj.dept}))
}

//加载管理层员工
function loadManager(){
    var data=commonAjax("post","/jx/wlb/selectCpkEmpByDeptAndInPostId",{pkDept:obj.dept})
    var footer = $("#dg").datagrid("getFooterRows");
    for (let d of data){
        let empName = d.empName;   //名字
        let postName = d.postName;  //职务
        if (postName=="叉车司机"){
            //叉车司机的主管工号
            let zhuguan=d.empZhuguan;
            //去数据库查询获取主管名字进行对比
            let result=commonAjax("post","/jxEmp/getEmpByPkDeptAndPostId",{empCode:zhuguan});
            var name=result[0].empName;
            d.empZhuguan = name;
        }
        if (footer){
            for(let f of footer){
                let empCode = f.empCode;   //主管名称
                let num=f.num;
                let resultMoney=f.resultMoney;
                if(empName==empCode){
                    let mean=Number(resultMoney)/num*1.4
                    mean=mean>800?800:mean;
                    d.performanceBonusNorm=fomatFloat(mean,2) //赋值绩效奖金

                }
                //叉车司机
                if (postName=="叉车司机") {
                    if (name == empCode) {
                        let mean = Number(resultMoney) / num * 0.9
                        mean = mean > 800 ? 800 : mean;
                        d.performanceBonusNorm = fomatFloat(mean, 2) //赋值绩效奖金
                        d.empZhuguan = name;
                    }
                }

            }
        }
    }
    $("#dg2").datagrid("loadData",data)
}

//加载绩效数据
function toLoadJxAssessWlb(){
    var year=obj.year;
    var month=obj.month;
    if (!year){
        windowsOperation(null,null,{status:200,msg:"请先选择日期!"})
        return;
    }
    var data=commonAjax("post","/jx/wlb/queryJxAssessWlbCpk",{year:year,month:month,type:obj.type})
    $("#dg").datagrid("loadData",data.a);
    $("#dg2").datagrid("loadData",data.b);
    $("#totalMoney").val(data.money);
}

//添加绩效数据
function addData() {
    //判断是否有选择日期
    var year = obj.year;
    if (!year){
        windowsOperation(null,null,{status:200,msg:"添加失败，请输入日期！"})
        return
    }
    var month = obj.month;
    var resultData;
    var rows = $("#dg").datagrid("getRows");
    var rows2 = $("#dg2").datagrid("getRows");
    for (let r of rows2){
        rows.push(r);
    }
    rows.forEach(function ( val) {
        val.assessYear=year;
        val.assessMonth=month;
    })
    //封装总合计
    var  totalMoney= $("#totalMoney").val();
    var jxAssessWlbTotal={};
    var jxAssessWlbTotals=[];
    jxAssessWlbTotal.assessYear=year;
    jxAssessWlbTotal.assessMonth=month;
    jxAssessWlbTotal.assessType=obj.type;    //配件组类型
    jxAssessWlbTotal.totalMoney=totalMoney;
    jxAssessWlbTotal.remarks="合计";
    jxAssessWlbTotals.push(jxAssessWlbTotal);
    resultData={"jxAssessWlbCpk":rows,jxAssessWlbTotals:jxAssessWlbTotals}
    resultData=JSON.stringify(resultData);
    var data= commonAjax("post","/jx/wlb/addCpkData",resultData,"application/json;charset=utf-8");
    windowsOperation(null,null,data)
}

//表字段
function tableColumns(val) {
    var result;
    result=[[
        {"field": 'empName', "title": '姓名', "width": '5%', "align": "center","editor": {"type": "text"}},
        {"field": 'empCode', "title": '工号', "width": '5%', "align": "center","editor": {"type": "text"}},
        {"field": 'empZhuguan', "title": '所属主管', "width": '5%', "align": "center","editor": {"type": "text"}},
        {"field": 'achieving',"title": '包装车间整<br>体计划达成<br>率',"width": '5%',"align": "center",
            "editor": {"type": "textbox","options": {onChange:producePrecisionOnChange}}},
        {"field": 'punctuality',"title": '准时率',"width": '5%',"align": "center",
            "editor": {"type": "textbox", "options": {onChange:producePrecisionOnChange}}},
        {"field": 'exact',"title": '准确率',"width": '5%',"align": "center",
            "editor": {"type": "textbox", "options": {onChange:producePrecisionOnChange}}},
        {"field": 'performanceBonusNorm', "title": '综合奖金基<br>数', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'score7S',"title": '7S分数',"width": '5%',"align": "center",
            "editor": {"type": "textbox", "options": {onChange:score7sOnChange}}},
        {"field": 'rp7S',"title": '7S得分',"width": '5%',"align": "center",
            "editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'attendanceRate', "title": '出勤率', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'otherAssess', "title": '其它扣款', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'otherAward', "title": '其它奖励', "width": '5%',"align": "center","editor": {"type": "textbox", "options": {onChange:resultMoneyOnChange}}},
        {"field": 'resultMoney', "title": '综合<br/>绩效（元）', "width": '8%',"align": "center","editor": {"type": "textbox", "options": {"readonly":true}}},
        {"field": 'remarks', "title": '备注',"width": '24%', "align": "center","editor": {"type":"textarea"}}
    ]]
    var postName= {"field": 'postName', "title": '职务', "width": '8%', "align": "center","editor": {"type": "combobox","options": {editable:false,valueField:"v",textField:"t",
                panelHeight:'auto',data:[{v:'成品仓务员',t:'成品仓务员'},{v:'半成品仓务员',t:'半成品仓务员'},{v:'水料仓务员',t:'水料仓务员'},{v:'账务员',t:'账务员'},{v:'账务主管',t:'账务主管'}]}}}
    var postName2= {"field": 'postName', "title": '职务', "width": '8%', "align": "center","editor": {"type": "combobox","options": {editable:false,valueField:"v",textField:"t",
                panelHeight:'auto',data:[{v:'仓务主管',t:'仓务主管'},{v:'成品出货主管',t:'成品出货主管'},{v:'账务主管',t:'账务主管'},{v:'叉车司机',t:'叉车司机'}]}}}
    switch (val) {
        case 1:
            result[0].splice(2,0,postName);
            break
        case 2:
            result[0].splice(2,0,postName2);
            break
    }
    return result;
}

//表对象
function Table() {
    this.type = 2;                    //成品科在统计表中的类型
    this.index = 1;
    this.index2 = 1;
    this.dept = '1002O110000000000MLC';   //成品科部门
    this.year = "";
    this.month = "";
    this.url = "";
    this.data = "";
    this.queryParams = {};
    this.tableInit = function () {
        $('#dg').edatagrid({
            width: '100%',
            height: document.getElementById("article").clientHeight,
            url: this.url,
            queryParams: this.queryParams,
            showFooter: true,
            autoSave: true,
            nowrap: false,
            columns: tableColumns(1),
            onLoadSuccess: data => {
                if (data.rows.length == 0) {
                    windowsOperation(null, null, {status: 200, msg:  + obj.month?"没有"+obj.month+"月的绩效数据！":"请选择日期查询数据！"})
                }
            },
            onBeforeEdit: function (index, row) {
                obj.index = index;
            },
            onBeginEdit: function (index, row) {
                var postName = editObj("postName");
                if (!postName.textbox("getValue")) {
                    postName.textbox("setValue", "成品仓务员")
                }

            },
            onAfterEdit: function () {
                console.log("触发")
                //页脚行、总合计
                calculateTotal()
            }
        });
    }
    this.tableInit2 = () => {
        $('#dg2').edatagrid({
            width: '100%',
            height: document.getElementById("article2").clientHeight,
            data: this.data,
            showFooter: true,
            autoSave: true,
            nowrap: false,
            columns: tableColumns(2),
            onLoadSuccess: data => {
                if (data.rows.length == 0) {
                    windowsOperation(null, null, {status: 200, msg:  + obj.month?"没有"+obj.month+"月的绩效数据！":"请选择日期查询数据！"})
                }
            },
            onBeforeEdit: function (index, row) {
                obj.index2 = index;
            },
            onAfterEdit: function () {

                //总合计
                calculateTotal()
            }
        });
    }
}

//总合计计算
function calculateTotal() {
    //需要每个主管中管理人员的总数、和人数
    let rows=$("#dg").datagrid("getRows");
    let result=[];     //[{empCode:"",resultMoney:"",num:1},{empCode:"",resultMoney:"",num:1}]
    let totalMoney=0;
    if (rows){
        for (let v  of rows){
            let empZhuguan = v.empZhuguan;                  //主管名称
            let resultMoney = v.resultMoney;                //绩效奖金
            resultMoney=resultMoney?Number(resultMoney):0;
            totalMoney+=resultMoney
            let flag=false;
            //循环
            for (let val of result){
                if(val.empCode==empZhuguan){
                    val.resultMoney=fomatFloat(Number(val.resultMoney)+resultMoney,2);
                    val.num++;
                    flag=true;
                    break;
                }
            }

            if (!flag){  //进入此条件证明是新值
                if (empZhuguan){
                    result.push({empCode:empZhuguan,resultMoney:resultMoney,num:1})
                }

            }
        }
        //重新加载页脚行
        $('#dg').datagrid('reloadFooter',result);
    }

    var rows2 = $("#dg2").datagrid("getRows");
    for (let row of rows2){
        let rm=row.resultMoney;
        rm=rm?Number(rm):0;
        totalMoney+=rm;
    }
    $("#totalMoney").val(fomatFloat(totalMoney,2));
}

//计算 奖金标准
function producePrecisionOnChange(){
    var achieving = editObj("achieving").textbox("getValue");       //achieving:包装车间整体达成率
    var exact = editObj("exact").textbox("getValue");               //准确率
    var punctuality = editObj("punctuality").textbox("getValue");   //准时率
    var result=0;
    var postName=editObj("postName").textbox("getValue");

    if (postName=="半成品仓务员"  || postName=="水料仓务员"  || postName.includes("账务")){  //账务员和账务员主管一样的计算方式
        if (achieving>=98) {  //包装车间整体达成率必须大于98
            if (exact>=99){   //正确率大于99
                if (98<punctuality && punctuality<99){
                    result=400;
                }
                if (99<=punctuality && punctuality<=100){
                    result=500;
                }
                if (exact==100 && punctuality==100){
                    result=600;
                }
            }

        }
    }

    //比较严格，就两个选择：要么600，要么没钱
    if (postName=="成品仓务员" || postName==("监装员")){
        if (exact==100 && punctuality==100){
            result=600;
        }

    }

    //主管和叉车司机不用计算
    if (postName=="成品出货主管" || postName=="仓务主管" || postName =="叉车司机"){
        return
    }

    var performanceBonusNorm = editObj("performanceBonusNorm");
    performanceBonusNorm.textbox("setValue",result);
}

//7s事件
function score7sOnChange(newValue) {
    var result=0;
    var performanceBonusNorm = editObj("performanceBonusNorm").textbox("getValue");
    performanceBonusNorm=performanceBonusNorm?performanceBonusNorm:0;
    var postName = editObj("postName").textbox("getValue"); //职务
    if (newValue>=75){
        if (postName.includes("仓务员")){
            result= Number(performanceBonusNorm)*0.1;
        }
        if (postName.includes("账务") || postName.includes("监装员")) {
            result = Number(performanceBonusNorm) * 0.05;
        }
    }else {
        if (postName.includes("仓务员")){
            result= -Number(performanceBonusNorm)*0.1;
        }
        if (postName.includes("账务") || postName.includes("监装员")) {
            result = -Number(performanceBonusNorm) * 0.05;
        }

    }
    editObj("rp7S").textbox("setValue",fomatFloat(result,2));
}

function resultMoneyOnChange() {
    var performanceBonusNorm = editObj("performanceBonusNorm").textbox("getValue"); //performanceBonusNorm 综合奖金基<br>数
    performanceBonusNorm=performanceBonusNorm?Number(performanceBonusNorm):0;
    var otherAssess = editObj("otherAssess").textbox("getValue");       //其它扣款
    otherAssess=otherAssess?Number(otherAssess):0;
    var otherAward = editObj("otherAward").textbox("getValue");         //其它奖励
    otherAward=otherAward?Number(otherAward):0;
    var attendanceRate = editObj("attendanceRate").textbox("getValue"); //出勤率
    attendanceRate=attendanceRate?Number(attendanceRate)/100:0;
    var rp7s = editObj("rp7S").textbox("getValue");                     //7s得分
    rp7s=rp7s?Number(rp7s):0;
    //start 计算
    var result=0;
    var postName = editObj("postName").textbox("getValue"); //职务
    if (postName.includes("仓务员")){
        //   S1=(C*90%+E*10%)*A1-D
        result=fomatFloat((performanceBonusNorm*0.9+rp7s)*attendanceRate-otherAssess+otherAward,2);
    }else if (postName.includes("账务") || postName=="监装员"){  //账务主管会先进这里，
        result=fomatFloat((performanceBonusNorm*0.95+rp7s)*attendanceRate-otherAssess+otherAward,2);
    }else if(postName.includes("主管") || postName=="叉车司机" ){
        result=fomatFloat(performanceBonusNorm*attendanceRate-otherAssess+otherAward,2);
    }

    var resultMoney = editObj("resultMoney"); //综合<br/>绩效（元）
    resultMoney.textbox("setValue",result)
}


function editObj(fieldName) {
    var result;
    try {
        result= $('#dg').datagrid("getEditor",{index:obj.index,field:fieldName}).target;
    }catch (e) {
        result= $('#dg2').datagrid("getEditor",{index:obj.index2,field:fieldName}).target;
    }
    return  result;
}
